import java.util.ArrayList;
import java.util.List;

public class Solution113 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root==null){
            return new ArrayList<>();
        }
        List<List<Integer>> ans=new ArrayList<>();
        List<Integer> temp=new ArrayList<>();
        dfs(root,temp,ans,targetSum,0);
        return ans;
    }

    private void dfs(TreeNode root, List<Integer> temp, List<List<Integer>> ans, int target, int sum) {
        if (root.left==null && root.right==null){
            if (sum+root.val==target){
                List<Integer> list=new ArrayList<>(temp);
                list.add(root.val);
                ans.add(list);
            }
            return;
        }
        temp.add(root.val);
        if (root.left!=null){
            dfs(root.left,temp,ans,target,sum+root.val);
        }
        if (root.right!=null){
            dfs(root.right,temp,ans,target,sum+root.val);
        }
        temp.remove(temp.size()-1);
    }

    public static void main(String[] args) {
        System.out.println(new Solution113().pathSum(new TreeNode(5,new TreeNode(4,new TreeNode(11,new TreeNode(7),new TreeNode(2)),null),new TreeNode(8,new TreeNode(13),new TreeNode(4,new TreeNode(5),new TreeNode(1)))),22));
    }
}
